import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { cloneDeep } from 'lodash-es'

// 组件接口定义
export interface ComponentItem {
  id: string
  type: string
  props: Record<string, any>
  style: {
    position: string
    top: number | string
    left: number | string
    width: number | string
    height: number | string
    [key: string]: any
  }
  events?: Record<string, string>
  children?: ComponentItem[]
  dataBindings?: Array<{propName: string, dataId: string}>
}

// 页面配置接口
export interface PageConfig {
  title: string
  description?: string
  components: ComponentItem[]
  style?: Record<string, any>
}

// 定义页面状态管理
export const usePageStore = defineStore('page', () => {
  // 页面配置
  const pageConfig = ref<PageConfig>({
    title: '未命名页面',
    description: '',
    components: [],
    style: {
      backgroundColor: '#f5f5f5',
      width: '100%',
      minHeight: '100%'
    }
  })

  // 当前选中的组件ID
  const selectedComponentId = ref<string | null>(null)

  // 历史记录 - 用于撤销/重做
  const history = ref<PageConfig[]>([])
  const historyIndex = ref(-1)
  const maxHistoryLength = 20

  // 获取当前选中的组件
  const selectedComponent = computed(() => {
    if (!selectedComponentId.value) return null
    return findComponentById(pageConfig.value.components, selectedComponentId.value)
  })

  // 递归查找组件
  const findComponentById = (components: ComponentItem[], id: string): ComponentItem | null => {
    for (const component of components) {
      if (component.id === id) {
        return component
      }
      if (component.children && component.children.length > 0) {
        const found = findComponentById(component.children, id)
        if (found) return found
      }
    }
    return null
  }

  // 添加组件
  const addComponent = (component: ComponentItem, parentId?: string) => {
    // 保存历史记录
    saveHistory()

    if (!parentId) {
      // 添加到根级
      pageConfig.value.components.push(component)
    } else {
      // 添加到指定父组件的子组件列表中
      const parent = findComponentById(pageConfig.value.components, parentId)
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(component)
      }
    }
    // 选中新添加的组件
    selectedComponentId.value = component.id
  }

  // 更新组件
  const updateComponent = (id: string, updates: Partial<ComponentItem>) => {
    // 保存历史记录
    saveHistory()

    const component = findComponentById(pageConfig.value.components, id)
    if (component) {
      // 更新组件属性
      if (updates.props) {
        component.props = { ...component.props, ...updates.props }
      }
      // 更新组件样式
      if (updates.style) {
        component.style = { ...component.style, ...updates.style }
      }
      // 更新组件事件
      if (updates.events) {
        component.events = { ...component.events, ...updates.events }
      }
      // 更新数据绑定
      if (updates.dataBindings) {
        component.dataBindings = [...updates.dataBindings]
      }
    }
  }

  // 移动组件位置
  const moveComponent = (id: string, newIndex: number, parentId?: string) => {
    // 保存历史记录
    saveHistory()

    let components = pageConfig.value.components
    
    // 如果有父组件ID，则获取父组件的子组件列表
    if (parentId) {
      const parent = findComponentById(components, parentId)
      if (parent && parent.children) {
        components = parent.children
      } else {
        return
      }
    }

    // 查找当前组件的索引
    const currentIndex = components.findIndex(item => item.id === id)
    if (currentIndex === -1) return

    // 移动组件
    const [component] = components.splice(currentIndex, 1)
    components.splice(newIndex, 0, component)
  }

  // 删除组件
  const removeComponent = (id: string) => {
    // 保存历史记录
    saveHistory()

    const removeFromArray = (components: ComponentItem[]) => {
      const index = components.findIndex(item => item.id === id)
      if (index !== -1) {
        components.splice(index, 1)
        return true
      }

      // 递归查找子组件
      for (const component of components) {
        if (component.children && component.children.length > 0) {
          if (removeFromArray(component.children)) {
            return true
          }
        }
      }

      return false
    }

    removeFromArray(pageConfig.value.components)
    
    // 如果删除的是当前选中的组件，则取消选中
    if (selectedComponentId.value === id) {
      selectedComponentId.value = null
    }
  }

  // 选择组件
  const selectComponent = (id: string | null) => {
    selectedComponentId.value = id
  }

  // 保存历史记录
  const saveHistory = () => {
    // 如果当前不是最新状态，则删除当前索引之后的历史记录
    if (historyIndex.value < history.value.length - 1) {
      history.value = history.value.slice(0, historyIndex.value + 1)
    }

    // 添加当前状态到历史记录
    history.value.push(cloneDeep(pageConfig.value))
    
    // 限制历史记录长度
    if (history.value.length > maxHistoryLength) {
      history.value.shift()
    } else {
      historyIndex.value++
    }
  }

  // 撤销操作
  const undo = () => {
    if (historyIndex.value > 0) {
      historyIndex.value--
      pageConfig.value = cloneDeep(history.value[historyIndex.value])
    }
  }

  // 重做操作
  const redo = () => {
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++
      pageConfig.value = cloneDeep(history.value[historyIndex.value])
    }
  }

  // 导出页面配置为JSON
  const exportJSON = () => {
    return JSON.stringify(pageConfig.value, null, 2)
  }

  // 导入页面配置
  const importJSON = (json: string) => {
    try {
      const config = JSON.parse(json) as PageConfig
      pageConfig.value = config
      // 重置历史记录
      history.value = [cloneDeep(config)]
      historyIndex.value = 0
      return true
    } catch (error) {
      console.error('导入JSON失败:', error)
      return false
    }
  }

  return {
    pageConfig,
    selectedComponentId,
    selectedComponent,
    addComponent,
    updateComponent,
    moveComponent,
    removeComponent,
    selectComponent,
    undo,
    redo,
    exportJSON,
    importJSON
  }
})